package controllers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import model.beans.Pair;
import model.daos.TeamDao;
import model.dtos.Team;
import views.windows.PositionsTablePanel;

public class PositionTableController extends PositionsTablePanel
{
	private static final long serialVersionUID = 1L;

	public PositionTableController()
	{
		super();
		fillGrid();
	}
	
	public void fillGrid()
	{
		String[][] data = null;
		List<Team> teams = new ArrayList<Team>((new TeamDao()).findAll());
		
		Collections.sort(teams, new Comparator<Team>() {
			
			public int compare(Team t1, Team t2)
			{
				return t1.getWonGames() > t2.getWonGames() ? -1 : (t1.getWonGames() == t2.getWonGames() ? (t1.getLostGames() < t2.getLostGames() ? -1 : (t1.getWonGames() == t2.getWonGames() ? 0 : 1)) : 1);
			}
			
		});
		
		List<Pair<Team, Integer>> dif = new ArrayList<Pair<Team, Integer>>();
		
		if (teams.size() > 0)
		{
			int wg = teams.get(0).getWonGames();
			int lg = teams.get(0).getLostGames();
			dif.add(new Pair<Team, Integer>(teams.get(0), 0));
			
			for (int i = 1; i < teams.size(); ++i)
				dif.add(new Pair<Team, Integer>(teams.get(i), ((wg - teams.get(i).getWonGames()) + (teams.get(i).getLostGames() - lg)) / 2));
			
			data = new String[dif.size()][6];
			
			for (int i = 0; i < dif.size(); ++i)
			{
				data[i][0] = dif.get(i).getLeft().getName();
				data[i][1] = String.valueOf(dif.get(i).getLeft().getPlayedGames());
				data[i][2] = String.valueOf(dif.get(i).getLeft().getWonGames());
				data[i][3] = String.valueOf(dif.get(i).getLeft().getLostGames());
				data[i][4] = String.valueOf(dif.get(i).getRight());
				data[i][5] = String.valueOf((dif.get(i).getLeft().getWonGames() * 1000) / dif.get(i).getLeft().getPlayedGames());
			}
		}
		
		TableModel tableModel = new DefaultTableModel(data, new String[] { "Equipo", "JJ", "JG", "JP", "Diferencia", "%" });
		getPositionsTable().setModel(tableModel);
		getPositionsTable().revalidate();
	}
}
